package com.kch.web.controller.monitor;

import com.kch.common.core.controller.BaseController;
import com.kch.common.core.domain.AjaxResult;
import com.kch.common.enums.OnlineStatus;
import com.kch.framework.shiro.session.OnlineSession;
import com.kch.framework.shiro.session.OnlineSessionDAO;
import com.kch.framework.util.ShiroUtils;
import com.kch.system.domain.SysUser;
import com.kch.system.domain.SysUserOnline;
import com.kch.system.service.ISysUserOnlineService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 在线用户监控
 *
 */
@Controller
@RequestMapping("/monitor/online")
@Api(tags = "用户退出")
public class SysUserOnlineController extends BaseController
{
    private String prefix = "monitor/online";

    @Autowired
    private ISysUserOnlineService userOnlineService;

    @Autowired
    private OnlineSessionDAO onlineSessionDAO;

    @GetMapping("/checkUserValid")
    @ApiOperation("检查当前登录用户是否有效")
    @ResponseBody
    public AjaxResult checkUserValid(){
        SysUser sysUser = ShiroUtils.getSysUser();
        if(!ObjectUtils.isEmpty(sysUser)){
           return AjaxResult.success(true);
        }else{
            return AjaxResult.success(false);
        }
    }

    @GetMapping("/logout")
    @ApiOperation("退出登录")
    @ResponseBody
    public AjaxResult forceLogout()
    {
        String session = getRequest().getHeader("Cookie");
        if(!ObjectUtils.isEmpty(session)){
            String sessionId = session.substring(session.indexOf("=") + 1);
            SysUserOnline online = userOnlineService.selectOnlineById(sessionId);
            if(!ObjectUtils.isEmpty(online)){
                OnlineSession onlineSession = (OnlineSession) onlineSessionDAO.readSession(online.getSessionId());
                onlineSession.setStatus(OnlineStatus.off_line);
                onlineSessionDAO.update(onlineSession);
                online.setStatus(OnlineStatus.off_line);
                userOnlineService.saveOnline(online);
                ShiroUtils.logout();
            }
        }
        return success();
    }
}
